package org.chnxi.algorithm.kmp;

/**
 * 字符串匹配-暴力匹配
 */
public class ViolenceMatch {

    public static void main(String[] args) {
        String str1 = "i like like like java, do you like java";
        String str2 = "like java";
        int idx = violenceMatch(str1 , str2);
        System.out.println("idx = "+idx);
    }

    /**
     * 使用暴力匹配获取str2在str1中首次出现的位置
     * @param str1 待匹配的字符串
     * @param str2 查找的字符串
     * @return 匹配到返回首次出现的索引位置，否则返回-1
     */
    public static int violenceMatch(String str1 , String str2){
        char[] s1 = str1.toCharArray();
        char[] s2 = str2.toCharArray();

        int s1Len = s1.length;
        int s2Len = s2.length;

        int i = 0;
        int j = 0;
        while (i < s1Len && j < s2Len){
            if(s1[i] == s2[j]){
                i++;
                j++;
            }else {
                i = i - (j-1);
                j = 0;
            }
        }

        if(j == s2Len){
            return i-j;
        }else{
            return -1;
        }
    }
}
